<script lang="ts" setup>
import { h, ref } from 'vue';
import { NButton, useMessage } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
type Song = {
  no: number;
  title: string;
  length: string;
  status: boolean;
};
// 全选
const checkedRowKeys = ref<any[]>([]);

const data = ref([
  { id: 1, key: 'sk-****HDj', date: new Date() },
  { id: 2, key: 'sn-Y*****dJDde', date: new Date() }
]);
// function formatDate(date: any) {
//   const year = date.getFullYear();
//   const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份加1，并补零
//   const day = String(date.getDate()).padStart(2, '0'); // 日期补零
//   const hours = String(date.getHours()).padStart(2, '0'); // 小时补零
//   const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟补零
//   const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒补零
//   return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
// }
// const formattedEndTime = formatDate(new Date())

const createColumns = ({
  play,
  editform
}: {
  play: (row: Song) => void;
  editform: (row: Song) => void;
}): DataTableColumns<Song> => {
  return [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      minWidth: 10,
      maxWidth: 100
    },
    {
      title: 'KEY',
      key: 'key',
      align: 'center',
      resizable: true
    },

    {
      title: '创建时间',
      key: 'date',
      align: 'center',
      resizable: true,
      minWidth: 100,
      maxWidth: 500
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h('div', { style: { display: 'flex', gap: '8px' } }, [
          h(
            'a',
            {
              style: { textDecoration: 'none', color: 'blue', cursor: 'pointer' },
              strong: true,
              tertiary: true,
              size: 'small',
              onClick: () => editform(row)
            },
            { default: () => '查看' }
          ),
          h(
            'a',
            {
              style: { textDecoration: 'none', color: 'blue', cursor: 'pointer' },
              strong: true,
              colorScheme: 'error',
              tertiary: true,
              size: 'small',
              onClick: () => play(row)
            },
            { default: () => '删除' }
          )
        ]);
      }
    }
  ];
};

const message = useMessage();
const visible = ref<boolean>(false);
const visible1 = ref<boolean>(false);
const type = ref<string>('');
const title = ref('新增');
// const originalData = ref<Song | null>(null); // 用于存储原始数据的副本
// 表单数据
const formRef = ref<any>(null);
const isEditMode = ref<boolean>(false);
const model = ref<any>({
  key: '',
  date: new Date()
});
const rules = ref({
  // word: {
  //   required: true,
  //   trigger: 'blur',
  //   message: '请输入敏感词',
  // },
  // sense_type: {
  //   required: true,
  //   trigger: 'blur',
  //   message: '请选择敏感词类型',
  // },
});
const handleButtonClick = (key: any) => {
  console.log(key, 'key');
  switch (key) {
    case 'addApi':
      visible.value = true;
      title.value = '新增API_KEY';
      model.value.key = '';
      break;
    case 'editApi':
      visible1.value = true;
      title.value = '查看API_KEY';
      break;
    default:
      break;
  }
  type.value = key;
};

// 关闭
const closeDrawer = () => {
  model.value = {
    key: ''
  };
  visible.value = false;
  visible1.value = false;
};

const handleSubmit = (e: any) => {
  e.preventDefault();
  switch (type.value) {
    case 'addApi':
      message.success('添加成功');
      break;
    case 'editApi':
      message.success('编辑成功');
      break;
    default:
      message.error('未知操作');
      break;
  }

  closeDrawer();
};

// 定义分页配置的接口类型
interface PaginationConfig {
  pageSize: number;
  page: number;
  // currentPage: number;
}

const pagination = ref<PaginationConfig>({
  pageSize: 10,
  page: 1 // 总页数，根据实际数据计算
  // currepagetPage: 1, // 当前页码
});
const play = () => {
  console.log('触发删除');
};
const editform = (row: Song) => {
  console.log(row, '编辑');
  // 在编辑前存储当前行数据的副本
  model.value = row;
  isEditMode.value = true;
  handleButtonClick('editApi');
};

const columns = createColumns({ play, editform });
// 分页
const handlePageChange = (newPage: number) => {
  console.log(`第${newPage}页`);

  pagination.value.page = newPage;
  // 在这里调用获取数据的函数，例如 fetchData(page.value, pageSize.value);
};

const handlePageSizeChange = (newPageSize: number) => {
  console.log(`一页${newPageSize}条`);
  pagination.value.pageSize = newPageSize;
  // 在这里调用获取数据的函数，例如 fetchData(page.value, pageSize.value);
};
// 全选反选
const handleCheck = (rowKeys: any) => {
  console.log('rowKeys :', rowKeys, 'checkedRowKeys :', checkedRowKeys.value);

  checkedRowKeys.value = rowKeys;
};
const handleAlldel = async () => {
  try {
    // 准备要删除的数据的 ID 数组
    const idsToDelete = checkedRowKeys.value;
    // 如果没有选中的项，则不执行删除
    if (idsToDelete.length === 0) {
      message.warning('请先选择要删除的项');
      return;
    }

    // 调用 API 进行批量删除
    // const response = await axios.post(apiDeleteUrl, { ids: idsToDelete });

    // 假设服务器返回了被删除的数据的 ID 数组
    // const deletedIds = response.data;
    // 从 data 和 checkedRowKeys 中移除已删除的数据
    // data.value = data.value.filter(item => !deletedIds.includes(item.id));
    checkedRowKeys.value = [];
    message.success('删除成功');
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除失败');
  }
};
</script>

<template>
  <div>
    <NCard>
      <div class="m-10px w-100% flex" style="justify-content: space-between">
        <NSpace justify="space-between">
          <NButton type="info" @click="handleButtonClick('addApi')">新增</NButton>
          <NButton type="info">禁用</NButton>
          <NButton type="info">启用</NButton>
          <NButton type="info" @click="handleAlldel">删除</NButton>
        </NSpace>
        <NSpace size="small">
          <NInput placeholder="搜索" clearable class="w-250px"></NInput>
        </NSpace>
      </div>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :row-key="row => row.id"
        :columns="columns"
        :data="data"
        :bordered="false"
        @update:checked-row-keys="handleCheck"
      />
      <NPagination
        v-model:page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-count="100"
        show-size-picker
        :page-sizes="[10, 20, 30, 40]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </NCard>
    <NDrawer
      v-model:show="visible"
      display-directive="show"
      :width="360"
      :on-mask-click="
        () => {
          visible = true;
        }
      "
    >
      <NDrawerContent :title="title" :native-scrollbar="false" closable>
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem label="API_KEY" path="key">
            <NInput v-model:value="model.key" placeholder="请输入API_KEY" />
          </NFormItem>
        </NForm>

        <template #footer>
          <NSpace :size="16">
            <NButton @click="closeDrawer">取消</NButton>
            <NButton type="primary" @click="handleSubmit">确定</NButton>
          </NSpace>
        </template>
      </NDrawerContent>
    </NDrawer>
    <NDrawer
      v-model:show="visible1"
      display-directive="show"
      :width="360"
      :on-mask-click="
        () => {
          visible1 = true;
        }
      "
    >
      <NDrawerContent :title="title" :native-scrollbar="false" closable>
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem label="API_KEY" path="key">
            <NInput v-model:value="model.key" disabled />
          </NFormItem>
          <NFormItem label="创建时间" path="date">
            <!-- <NInput v-model:value="model.date" disabled /> -->
            <!-- <n-time :time="model.date" /> -->
            <NDatePicker v-model:value="model.date" type="date" format="yyyy-MM-dd" readonly disabled />
          </NFormItem>
        </NForm>

        <template #footer>
          <NSpace :size="16">
            <NButton @click="closeDrawer">取消</NButton>
            <NButton type="primary" @click="handleSubmit">确定</NButton>
          </NSpace>
        </template>
      </NDrawerContent>
    </NDrawer>
  </div>
</template>

<style scoped></style>
